local tair_manager = require("ngx.tair")

local function print_result(status,body)
    ngx.header["Content-Type"] = 'application/json'
    ngx.status = status
    if body then
        ngx.print(body)
    end
    return ngx.exit(ngx.OK)
end

local function get_tair(group)
    if not group then
        ngx.log(ngx.INFO, "[UFE]tair group not set")
        return nil
    end

    local tair,msg = tair_manager:init(group)
    if not tair then
        ngx.log(ngx.INFO, "[UFE]tair group not found:", group)
        return nil
    end

    return tair
end

local function tair_get(group, ns, key)

    local tair = get_tair(group)
    if not tair then return print_result(ngx.HTTP_NOT_FOUND, string.format("cannot get tair:%s", group)) end

    local request = {["data"] = {{["key"] = key}}}
    local res,code,msg = tair:mget(ns, request)

    if code == 0 and res.data[1] then
        if res.data[1].code == 0 then
            return print_result(ngx.HTTP_OK ,res.data[1].value)
        elseif res.data[1].code == -3998 then
            ngx.log(ngx.INFO, string.format("[UFE]tair key not found. namespace:%s key:%s", ns, key))
            return print_result(ngx.HTTP_NOT_FOUND,"key not found")
        else
            ngx.log(ngx.ERR, string.format("[UFE]tair encounter unknown errors. namespace: namespace:%s key:%s",ns , key))
            return print_result(ngx.HTTP_INTERNAL_SERVER_ERROR, "tair encoutner unknown errors")
        end
    end
    return print_result(ngx.HTTP_SERVICE_UNAVAILABLE, "connect tair errors")
end

local group = ngx.var.arg_group
local ns = tonumber(ngx.var.arg_ns)
local key = ngx.var.arg_key
local method = ngx.var.request_method

if method ~= "GET" then
    return print_result(ngx.HTTP_NOT_ALLOWED, "Not Allowled");
end
if not group or not ns or not key then
    return print_result(ngx.HTTP_BAD_REQUEST,"Wrong Args")
end

return tair_get(group, ns, key)
